<?php

namespace app\user\event\listeners\user;

use app\course\logic\coupon\CouponUser;
use app\user\logic\user\Account;
use app\user\logic\user\TicketCoupon;

/**
 * 用户活动券发放
 */
class UserTicket
{
    public static function handle(Account $user)
    {
        // 参数
        $tickets = $user['ticket'] ?? [];

        foreach ($tickets as $ticket) {
            $ticket = app(TicketCoupon::class)->findOrEmpty($ticket['id']);

            CouponUser::create([
                'user_id'     => $user->id,
                'mhm_id'      => $ticket->mhm_id,
                'coupon_type' => $ticket->coupon_type,
                'ticket_id'   => $ticket->id,
                'end_time'    => $ticket->effective_day ? (time() + $ticket->effective_day * 86400) : null
            ]);

            $ticket->derive_number += 1;
            $ticket->save();
        }
    }
}
